#计算MA均值
import os

import numpy as np
import pandas as pd
from Utils.DataLoaderAndSaver import DataLoaderAndSaver
from Utils.configs import daysBefore1, daysBefore2, yearsBefore


class QuantileFeatureCalculation:
    def __init__(self,daysBefore1=0,daysBefore2=1,yearsBefore=4):
        #基本的配置信息
        self.quantileDays=[122,244,366,488,610,732]
        # self.maColumns=["date","code","close","ma_5","ma_10","ma_20","ma_30","ma_40","ma_50","ma_60","ma_70","ma_80",
        #                 "ma_90","ma_100","ma_120","ma_122","ma_150","ma_180","ma_200","ma_244","ma_250"]
        self.quantileTable='table_quantile'
        self.dataLoaderAndSaver=DataLoaderAndSaver(daysBefore1=daysBefore1,daysBefore2=daysBefore2,yearsBefore=yearsBefore)
        self.codes=self.dataLoaderAndSaver.allstocks.index
        self.dailyprices=self.dataLoaderAndSaver.dailyprices

    #计算历史的MA均线
    def calQuantile(self):
        #先删除历史表格，再重新写入
        try:
            self.dataLoaderAndSaver.dropTable(self.quantileTable)
        except:
            print('正常删除表格%s'%self.quantileTable)
        if os.path.exists('localData/quantile/'+self.dataLoaderAndSaver.todayDate+'.csv'):
            df=pd.read_csv('localData/quantile/'+self.dataLoaderAndSaver.todayDate+'.csv')
            df=df.drop('Unnamed: 0',axis=1)
            print(df)
            self.dataLoaderAndSaver.saveData(self.quantileTable, df, if_exists='replace')
            return
        res=[]
        for code in self.codes:
            try:
                prices = self.dailyprices[self.dailyprices['code'] == code]
                prices=prices[prices['close']!=np.nan]
                prices.index=pd.to_datetime(prices['date'])
                # print(prices.shape,prices.head(10))
                tmpdict={}
                tmpdict['code'] = [code]
                date=list(prices.tail(1).index)[0]
                tmpdict['date']=[date]
                current_price=list(prices['close'].tail(1))[0]
                tmpdict['close']=[current_price]
                for day in self.quantileDays:
                    theprice=prices.tail(day).head(day-1)
                    quantile=self.__calQuantile(current_price,theprice)
                    tmpdict['quant_'+str(day)]=[quantile]
                df=pd.DataFrame.from_dict(tmpdict)
                print(df)
                res.append(df)
                # self.dataLoaderAndSaver.saveData(self.quantileTable,df,if_exists='append')
            except:
                print(code, '计算失败')
                with open('log/'+self.dataLoaderAndSaver.todayDate + '_ma_fail.txt', 'a+', encoding='utf8') as f:
                    f.write(code + '\n')
                continue
        if len(res)>0:
            resdf=pd.concat(res,axis=0)
            resdf.to_csv('localData/quantile/'+self.dataLoaderAndSaver.todayDate+'.csv')
            print(resdf)
            self.dataLoaderAndSaver.saveData(self.quantileTable, resdf, if_exists='append')

    #计算分位数
    def __calQuantile(self,current_price,previous_prices):
        previous_prices=list(previous_prices['close'])
        previous_prices.sort()
        count=0
        for i in range(len(previous_prices)):
            if current_price>=previous_prices[i]:
                count=count+1
            else:
                break
        return round(count/len(previous_prices),2)
#
qfc=QuantileFeatureCalculation(daysBefore1=daysBefore1,daysBefore2=daysBefore2,yearsBefore=yearsBefore)
qfc.calQuantile()

